import React, {FunctionComponent, useEffect, useMemo, useState} from "react";
import {Button, Col, Row, Popover, Radio, message, Form, Input, Space, Modal} from "antd";
import {Post, Delete} from "para-lib";
import {
    EllipsisOutlined,
    FileTextTwoTone,
    PlusCircleOutlined,
    MinusCircleOutlined,
    PlusOutlined,
    createFromIconfontCN
} from "@ant-design/icons";
import {connect} from "react-redux";
import {API_CONFIG} from "../../config/api.config";

import "./index.less";

// 单次加载的表单的个数
const size = 20;

const IconFont = createFromIconfontCN({
    scriptUrl: "//at.alicdn.com/t/font_2882598_n9kom3lrz4.js"
});

const Home: FunctionComponent<any> = () => {
    // 表单的列表
    const [listData, setListData] = useState<any[]>([]);
    // 快速访问列表
    const [topList, setTopList] = useState<any[]>([]);
    // 页数
    const [page, setPage] = useState<number>(1);
    // 是否有数据
    const [noData, setNoData] = useState<boolean>(false);
    // 分享的地址
    const [shareUrl, setShareUrl] = useState<string>("");
    // 弹框显示影藏
    const [visible, setVisible] = useState<boolean>(false);
    // 分享表单初始值
    const [initialValues, setInitialValues] = useState<any[]>([]);

    // 获取表单列表
    const getListData = async () => {
        const {data, err} = await Post({
            url: API_CONFIG.form.list,
            data: {
                size: size * page,
                page: 1
            }
        });
        if (err) return;
        if (data.data) {
            setListData(data.data.list);
            if (data.data.total <= (size * page)) {
                setNoData(true);
            }
        }
    };

    const getQuickData = async () => {
        const {data, err} = await Post({
            url: API_CONFIG.form.quick,
            data: {}
        });
        if (err) return;
        if (data.data) {
            setTopList(data.data);
        }
    };

    // 删除表单
    const deleteForm = async (id: string) => {
        const {err} = await Delete({
            url: API_CONFIG.form.delete + id
        });
        if (err) return;
        message.success("删除成功");
        getListData();
        getQuickData();
    };

    // 加载更多
    const loadMore = () => {
        setPage(page + 1);
    };

    // 跳转到设计器页面
    const linkToForm = (id?: string) => {
        window.open(id ? `design.html?form=${id}` : "design.html");
    };

    // 预览表单
    const previewForm = (id?: string) => {
        window.open(`preview.html?form=${id}`);
    };

    // 点击分享
    const shareForm = (id: string) => {
        let originUrl = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : ""); // 兼容IE的origin值
        let url = originUrl + `/preview.html?form=${id}`;
        setShareUrl(url);
        setInitialValues([]);
        setVisible(true);
    };


    const content = (id: string) => {
        return (
            <div>
                <Radio.Group value={size}>
                    <Radio.Button value="edit" onClick={() => linkToForm(id)}>编辑</Radio.Button>
                    <Radio.Button value="delete" onClick={() => deleteForm(id)}>删除</Radio.Button>
                    <Radio.Button value="preview" onClick={() => shareForm(id)}>分享</Radio.Button>
                </Radio.Group>
            </div>
        );
    };

    // 邮箱分享的api
    const shareFormApi = async (data: any) => {
        const {err} = await Post({
            url: API_CONFIG.form.share,
            data
        });
        if (err) return;
        message.success("分享成功");
        closeDialog();

    };
    // 表单提交
    const onFinish = (values: any) => {
        const result = values.users;
        if (result.length <= 0) {
            message.warning("请添加分享人");
            return;
        }
        result.forEach((item: any) => {
            item.text = "上海派拉软件股份有限公司";
            item.subject = "您有新的表单待填写";
            item.message = "邀请您填写问卷";
            item.url = shareUrl;
        });
        shareFormApi(result);
    };

    // 关闭弹框
    const closeDialog = () => {
        setVisible(false);
        setInitialValues([]);
    };

    useEffect(() => {
        getListData();
    }, [page]);

    useEffect(() => {
        getQuickData();
    }, []);


    const list1 = useMemo(() => {
        return topList.map((item: any) => {
            return (
                <div className="small-item">
                    <div className="icon-box" onClick={() => previewForm(item._id)}>
                        <IconFont type="icon-biaoge"/>
                    </div>
                    <div className="detail" onClick={() => previewForm(item._id)}>
                        <div>{item.tableAlias || item.tableName}</div>
                        <div>{item?.userId?.username} &nbsp;&nbsp;最后更新于&nbsp;&nbsp;{item.updatedTime}</div>
                    </div>
                    <div className="icon-box">
                        <Popover placement="bottom" content={() => content(item._id)} title="操作" trigger="click">
                            <EllipsisOutlined/>
                        </Popover>
                    </div>
                </div>
            );
        });
    }, [topList]);

    const list2 = useMemo(() => {
        return listData.map((item: any) => {
            return (
                <div className="big-item" key={item._id}>
                    <div className="img-box" onClick={() => previewForm(item._id)}>
                        <img src={item?.blobId?.blobUrl} alt=""/>
                    </div>
                    <div className="small-item">
                        <div className="icon-box" onClick={() => previewForm(item._id)}>
                            <IconFont type="icon-biaoge"/>
                        </div>
                        <div className="detail" onClick={() => previewForm(item._id)}>
                            <div>{item.tableAlias || item.tableName}</div>
                            <div>{item?.userId?.username} &nbsp;&nbsp;最后更新于&nbsp;&nbsp;{item.updatedTime}</div>
                        </div>
                        <div className="icon-box">
                            <Popover placement="bottom" content={() => content(item._id)} title="操作" trigger="click">
                                <EllipsisOutlined/>
                            </Popover>
                        </div>
                    </div>
                </div>
            );
        });
    }, [listData]);

    return (
        <div className={"home"} style={{overflow: "auto"}}>
            <Row justify={"center"} wrap>
                {/*标题*/}
                <Col span={24} className="sub-header">
                    <span className="title">表单管理</span>
                    <Button type="primary" icon={<PlusCircleOutlined/>} onClick={() => linkToForm()}>新建</Button>
                </Col>
                {
                    topList.length > 0 && (
                        <Col span={24} className="content">
                            <div className="title">快速访问</div>
                            <div className="list-box">{list1}</div>
                        </Col>
                    )
                }
                {
                    listData.length > 0 ? (
                        <Col span={24} className="content">
                            <div className="title">最近</div>
                            <div className="list-box">{list2}</div>
                        </Col>
                    ) : (
                        <Col span={24} className="content">
                            <div className="load-more">暂无数据</div>
                        </Col>
                    )
                }

                {
                    (!noData && listData.length > 0) && (
                        <Col span={24} className="content">
                            <div onClick={loadMore} className="load-more active">加载更多</div>
                        </Col>
                    )
                }

            </Row>

            <Modal
                title="分享邀请"
                visible={visible}
                onOk={() => setVisible(false)}
                onCancel={() => setVisible(false)}
                footer={null}
            >
                <Form name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off"
                      initialValues={{users: initialValues}} className="form-dialog">
                    <Form.List name="users">
                        {(fields, {add, remove}) => (
                            <>
                                {fields.map(({key, name, fieldKey, ...restField}) => (
                                    <Space key={key} style={{display: "flex", marginBottom: 8}} align="baseline">
                                        <Form.Item
                                            {...restField}
                                            name={[name, "to"]}
                                            fieldKey={[fieldKey, "to"]}
                                            rules={[{required: true, message: "该项必填"}, {
                                                type: "email",
                                                message: "邮箱格式错误！"
                                            }]}
                                        >
                                            <Input placeholder="用户邮箱"/>
                                        </Form.Item>
                                        <MinusCircleOutlined onClick={() => remove(name)}/>
                                    </Space>
                                ))}
                                <Form.Item>
                                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined/>}>
                                        增加用户
                                    </Button>
                                </Form.Item>
                            </>
                        )}
                    </Form.List>
                    <Form.Item className="button-list">
                        <Button htmlType="reset" onClick={closeDialog}>
                            取消
                        </Button>
                        <Button type="primary" htmlType="submit">
                            分享
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default connect((state: { audit: any }) => ({}))(Home);
